{%- assign facebook = storeConfig.facebook_pixel_config | strtoarray -%}
{% get_pixels_domain list={facebook} %}
{% assign facebook = list | pixelRemarkFilter: 'fbcode' %}
{% assign pixel_facebook_amount_percent = storeConfig.pixel_facebook_amount_percent | default: 100 %}
{%- if facebook -%}
  <!-- Facebook Pixel Code -->
  <script>
        !function (f, b, e, v, n, t, s) {
            if (f.fbq) return;
            n = f.fbq = function () {
                n.callMethod ? n.callMethod.apply(n, arguments) : n.queue.push(arguments)
            };
            if (!f._fbq) f._fbq = n;
            n.push = n;
            n.loaded = !0;
            n.version = '2.0';
            n.queue = [];
            t = b.createElement(e);
            t.async = !0;
            t.src = v;
            s = b.getElementsByTagName(e)[0];
            s.parentNode.insertBefore(t, s)
        }(window, document, 'script', 'https://connect.facebook.net/en_US/fbevents.js');
        var fb_eventid = (new Date()).getTime() + '.' + Math.ceil(Math.random() * 10000000) + '.' + Math.ceil(Math.random() * 10000000);

        function yfbservertag(event_name, obj, event_id) {
                //Pay success callback
                const purchase = {
                    em: '{% if pixel_user.email %}{{pixel_user.email | string_sha256 }}{% endif %}',
                    ph:"{% if pixel_user.phone_number %}{{ pixel_user.phone_number | pixelPhoneNumberFormat:'facebook',pixel_user.tel_area_code }}{% endif %}",
                    country:"{% if country %}{{country | strtolower| string_sha256}}{% endif %}" 
                };
                {%- if controller == 'order' and action == 'success' -%}
                purchase.ln = "{% if order.shipping_address.last_name %}{{order.shipping_address.last_name | strtolower | fbValidateAndEncode | string_sha256}}{% endif %}";
                purchase.fn = "{% if order.shipping_address.first_name %}{{order.shipping_address.first_name | strtolower | fbValidateAndEncode | string_sha256}}{% endif %}";
                purchase.ct = "{% if order.shipping_address.city %}{{order.shipping_address.city | strtolower | fbValidateAndEncode| string_sha256}}{% endif %}";
                purchase.st = "{% if order.shipping_address.province %}{{order.shipping_address.province | strtolower | string_sha256}}{% endif %}";
                purchase.zp = "{% if order.shipping_address.zip %}{{order.shipping_address.zip | str_preg_replace | strtolower | string_sha256}}{% endif %}";
                purchase.country = "{% if order.shipping_address.country_code %}{{order.shipping_address.country_code | strtolower| string_sha256}}{% endif %}";
                {%- endif -%}

                const fbParams = {
                    /*********  start   ********/
                    "visitor_id": _GET_C_SETTING_('global_unique_id'),
                    "country_code": _GET_C_SETTING_('client_country'),
                    "event_name": event_name,
                    "event_id": event_id,
                    "event_source_url": location.href,
                    "action_source": 'website',
                    "user_data": {
                        "fbcode":_G_COLLECT.getCookie("fbcode") || "",
                        "client_user_agent": navigator.userAgent,
                        "fbc": _G_COLLECT.getCookie("_fbc") || `{{request_param|facebookfbc}}`,
                        "fbp": _G_COLLECT.getCookie("_fbp") || '{{1|facebookfbp}}',
                        ...purchase
                    },
                    "custom_data": obj
                }
                fetch('/homeapi/facebook', {
                    method: "POST",
                    body: JSON.stringify(fbParams)
                })
        };
             
            {% for pixel in facebook %}
            fbq('init', '{{ pixel.pixel_id }}', {% if pixel_user.id %}{external_id:'{{ pixel_user.id | string_sha256 }}'}{% else %}{}{% endif %}, {}, {eventID: fb_eventid});
            fbq('trackSingle', '{{ pixel.pixel_id }}', 'PageView', {'event_category': '{{template}}'}, {eventID: fb_eventid});
            {% endfor %}
            yfbservertag('PageView',{'event_category': '{{template}}'}, fb_eventid);

        {%- if template == 'product_detail' -%}
            const fbqViewContentParams = {
                content_name:  _GET_C_SETTING_('product').title,
                content_category: '{{product.product_type | filter_string_format}}',
                value: '{{ product.variant.price|times:pixel_facebook_amount_percent|divided_by:100}}',
                content_type: 'product',
                {% if storeConfig.pixel_facebook_content_id == 'sku_code' %}
                    content_ids: `{{product.variant.sku_code}}`,
                {% else %}
                    content_ids: `{{product.spu}}`,
                {% endif %}
                currency: '{{ base_currency.standard_code }}'
            };
            {%- for pixel in facebook -%}
            fbq('trackSingle', '{{ pixel.pixel_id }}', 'ViewContent', fbqViewContentParams, {eventID: fb_eventid});
            {%- endfor -%}
            yfbservertag('ViewContent',fbqViewContentParams,fb_eventid)
        
        {%- elsif template == 'search_detail' and search.keywords -%}
            const fbqSearchParams = {
                search_string: '{{search.keywords | filter_string_format}}',
                content_type: 'product',
                currency: _GET_C_SETTING_('currency_code'),
                contents:[]
            };
            {%- for product in search.products -%}
            fbqSearchParams.contents.push({
                {% if storeConfig.pixel_facebook_content_id == 'sku_code' %}
                id:'{{ product.variant.sku_code}}',
                {% else %}
                id: '{{ product.spu  | escape }}',
                {% endif %}
                quantity: 1,
                item_price: "{{ product.variant.price }}"
            });
            {%- endfor -%}

            {%- for pixel in facebook -%}
            fbq('trackSingle', '{{ pixel.pixel_id }}', 'Search', fbqSearchParams, {eventID: fb_eventid});
            {%- endfor -%}
            yfbservertag('Search',fbqSearchParams,fb_eventid)

        {%- elsif controller == 'order' and action == 'success' -%}
            const fbqPurchaseParams = {
                {% if storeConfig.facebook_sales_goods_amount %}
                value: "{{ order.current_subtotal_price| plus: order.current_coupon_price| plus: order.current_promotion_price|times:pixel_facebook_amount_percent|divided_by:100 }}",
                {% else %}
                value: "{{ order.total_price|times:pixel_facebook_amount_percent|divided_by:100 }}",
                {% endif %}
                currency: '{{ order.currency_code }}',
                contents:[],
                content_type:'product',
                order_id: '{{order.order_number}}',
                num_items: '{{order.total_num}}'
            };
            {%- for product in order.products -%}
                fbqPurchaseParams.contents.push({
                    {% if storeConfig.pixel_facebook_content_id == 'sku_code' %}
                    id: `{{product.sku_code}}`,
                    {% else %}
                    id: `{{product.spu  | escape}}`,
                    {% endif %}
                    quantity: "{{ product.quantity }}",
                    item_price: "{{ product.discount_price  | default : product.price }}"
                });
            {%- endfor -%}

            {% capture pixels %}facebook_pixels_{{order.id}}{% endcapture %}
            {% get_cache key={pixels} var_name=facebook_pixels_status ttl=2592000 %}
            {% if facebook_pixels_status == 0 %}

            {%- for pixel in facebook -%}
            fbq('trackSingle', '{{ pixel.pixel_id }}', 'Purchase', fbqPurchaseParams, {eventID: "{{order.order_number}}"});
            {%- endfor -%}
            {% comment %} yfbservertag('Purchase', fbqPurchaseParams, '{{order.order_number}}'); {% endcomment %}

            {% endif %}
        {%- elsif template == 'order_payment_gateway' and order.payment_type == 'offlinepay' and storeConfig.is_offlinepay_purchase_pixel == '1' -%}
            const fbqPurchaseParams = {
                {% if storeConfig.facebook_sales_goods_amount %}
                value: "{{ order.current_subtotal_price| plus: order.current_coupon_price| plus: order.current_promotion_price|times:pixel_facebook_amount_percent|divided_by:100 }}",
                {% else %}
                value: "{{ order.total_price|times:pixel_facebook_amount_percent|divided_by:100 }}",
                {% endif %}
                currency: '{{ order.currency_code }}',
                contents:[],
                content_type:'product',
                order_id: '{{order.order_number}}',
                num_items: '{{order.total_num}}'
            };
            {%- for product in order.products -%}
                fbqPurchaseParams.contents.push({
                    {% if storeConfig.pixel_facebook_content_id == 'sku_code' %}
                    id: `{{product.sku_code}}`,
                    {% else %}
                    id: `{{product.spu  | escape}}`,
                    {% endif %}
                    quantity: "{{ product.quantity }}",
                    item_price: "{{ product.discount_price  | default : product.price }}"
                });
            {%- endfor -%}
            {% capture pixels %}facebook_pixels_{{order.id}}{% endcapture %}
            {% get_cache key={pixels} var_name=facebook_pixels_status ttl=2592000  %}
            {% if facebook_pixels_status == 0 %}
            {%- for pixel in facebook -%}
            fbq('trackSingle', '{{ pixel.pixel_id }}', 'Purchase', fbqPurchaseParams, {eventID: "{{order.order_number}}"});
            {%- endfor -%}
            {% endif %}

        {%- elsif template == 'blog_detail' -%}
            const fbqBlogParams = {
                'event_category': '{{template}}',
                'event_label': '{{blog.title | escape}}',
                'event_value': '{{blog.id}}'
            };
            {%- for pixel in facebook -%}
            fbq('trackSingleCustom', '{{ pixel.pixel_id }}', 'page_view_event',fbqBlogParams, {eventID: fb_eventid});
            {%- endfor -%}
            yfbservertag('page_view_event',fbqBlogParams, fb_eventid);

        {%- elsif template == 'collection_detail' -%}
            const fbqCollectionParams = {
                'event_category': '{{template}}',
                'event_label': '{{collection.title | escape}}',
                'event_value': '{{collection.id}}'
            };
            {%- for pixel in facebook -%}
            fbq('trackSingleCustom', '{{ pixel.pixel_id }}', 'page_view_event',fbqCollectionParams, {eventID: fb_eventid});
            {%- endfor -%}
            yfbservertag('page_view_event',fbqCollectionParams, fb_eventid);
        {%- elsif template == 'page_detail' -%}
            const fbqPageParmas = {
                'event_category': '{{template}}',
                'event_label': '{{page.title | escape}}',
                'event_value': '{{page.id}}'
            };
            {%- for pixel in facebook -%}
            fbq('trackSingleCustom', '{{ pixel.pixel_id }}','page_view_event',fbqPageParmas, {eventID: fb_eventid});
            {%- endfor -%}
            yfbservertag('page_view_event',fbqPageParmas, fb_eventid);

        {%- endif -%}
  </script>
  {%- for pixel in facebook -%}
    <noscript><img
        height='1'
        width='1'
        src='https://www.facebook.com/tr?id="{{ pixel.pixel_id }}"&ev=pageview&noscript=1' />
    </noscript>
  {%- endfor -%}


  <script>
    function callback_facebook_add_to_cart(ecdata) {
        {%- if facebook -%}
            var fb_eventid = (new Date()).getTime() + '.' + Math.ceil(Math.random() * 10000000) + '.' + Math.ceil(Math.random() * 10000000);
            const fbqAddToCartParmas = {
                content_type: 'product',
                content_category: ecdata['ec_data_category'],
                content_name: ecdata['ec_data_name'],
                currency: "{{ base_currency.standard_code }}",
                value: ecdata['ec_data_price']*ecdata['ec_data_quantity'],
                contents: [{
                    {% if storeConfig.pixel_facebook_content_id == 'sku_code' %}
                    id: ecdata['ec_data_sku_code'], 
                    {% else %}
                    id: ecdata['ec_data_spu'], 
                    {% endif %}
                    quantity: ecdata['ec_data_quantity'], item_price: ecdata['ec_data_price']}]
            };
            {%- for pixel in facebook -%}
            fbq('trackSingle', '{{ pixel.pixel_id }}', 'AddToCart', fbqAddToCartParmas, {eventID: fb_eventid});
            {%- endfor -%}
            yfbservertag('AddToCart',fbqAddToCartParmas, fb_eventid);
        {%- endif -%}
    }

    function callback_facebook_generate_lead() {
        {%- if facebook -%}
            var fb_eventid = (new Date()).getTime() + '.' + Math.ceil(Math.random() * 10000000) + '.' + Math.ceil(Math.random() * 10000000);
            {%- for pixel in facebook -%}
            fbq('trackSingle', '{{ pixel.pixel_id }}', 'Lead', {}, {eventID: fb_eventid});
            {%- endfor -%}
            yfbservertag('Lead', {}, fb_eventid);
        {%- endif -%}
    }

    function callback_facebook_login() {
        {%- if facebook -%}
            var fb_eventid = (new Date()).getTime() + '.' + Math.ceil(Math.random() * 10000000) + '.' + Math.ceil(Math.random() * 10000000);
            {%- for pixel in facebook -%}
            fbq('trackSingleCustom', '{{ pixel.pixel_id }}', 'login',{}, {eventID: fb_eventid});
            {%- endfor -%}
            yfbservertag('login',{}, fb_eventid);
        {%- endif -%}
    }

    function callback_facebook_begin_checkout() {
        {%- if facebook -%}
            var fb_eventid = (new Date()).getTime() + '.' + Math.ceil(Math.random() * 10000000) + '.' + Math.ceil(Math.random() * 10000000);
            {%- for pixel in facebook -%}
            fbq('trackSingle', '{{ pixel.pixel_id }}', 'InitiateCheckout', {}, {eventID: fb_eventid});
            {%- endfor -%}
            yfbservertag('InitiateCheckout',{}, fb_eventid);
        {%- endif -%}
    }

    function callback_facebook_share_product(ecdata, platform) {
        {%- if facebook -%}
            var fb_eventid = (new Date()).getTime() + '.' + Math.ceil(Math.random() * 10000000) + '.' + Math.ceil(Math.random() * 10000000);
            const fbqShareProductParams = {
                'event_category':ecdata['ec_data_category'],
                'event_label':ecdata['ec_data_spu'],
                'event_value':ecdata['ec_data_quantity']
            };
            {%- for pixel in facebook -%}
            fbq('trackSingleCustom', '{{ pixel.pixel_id }}', 'share_product',fbqShareProductParams, {eventID: fb_eventid});
            {%- endfor -%}
            yfbservertag('share_product',fbqShareProductParams,fb_eventid);
        {%- endif -%}
    }

    function callback_facebook_remove_from_cart(ecdata) {
        {%- if facebook -%}
            var fb_eventid = (new Date()).getTime() + '.' + Math.ceil(Math.random() * 10000000) + '.' + Math.ceil(Math.random() * 10000000);
            const fbqRemoveFromCart = {
                'event_category':ecdata['ec_data_category'],
                'event_label':ecdata['ec_data_spu'],
                'event_value':ecdata['ec_data_quantity']
            };
            {%- for pixel in facebook -%}
            fbq('trackSingleCustom', '{{ pixel.pixel_id }}', 'remove_from_cart',fbqRemoveFromCart, {eventID: fb_eventid});
            {%- endfor -%}
            yfbservertag('remove_from_cart',fbqRemoveFromCart, fb_eventid);
        {%- endif -%}
    }

    function callback_facebook_sign_up() {
        {%- if facebook -%}
            var fb_eventid = (new Date()).getTime() + '.' + Math.ceil(Math.random() * 10000000) + '.' + Math.ceil(Math.random() * 10000000);
            {%- for pixel in facebook -%}
            fbq('trackSingle', '{{ pixel.pixel_id }}', 'CompleteRegistration',{}, {eventID: fb_eventid});
            {%- endfor -%}
            yfbservertag('CompleteRegistration',{}, fb_eventid);
        {%- endif -%}
    }

    function callback_facebook_add_address_information() {
        {%- if facebook -%}
            var fb_eventid = (new Date()).getTime() + '.' + Math.ceil(Math.random() * 10000000) + '.' + Math.ceil(Math.random() * 10000000);
            {%- for pixel in facebook -%}
            fbq('trackSingleCustom', '{{ pixel.pixel_id }}', 'add_address_information',{}, {eventID: fb_eventid});
            {%- endfor -%}
            yfbservertag('add_address_information',{}, fb_eventid);
        {%- endif -%}
    }

    function callback_facebook_add_shipping_information() {
        {%- if facebook -%}
            var fb_eventid = (new Date()).getTime() + '.' + Math.ceil(Math.random() * 10000000) + '.' + Math.ceil(Math.random() * 10000000);
            {%- for pixel in facebook -%}
            fbq('trackSingleCustom', '{{ pixel.pixel_id }}', 'add_shipping_information',{}, {eventID: fb_eventid});
            {%- endfor -%}
            yfbservertag('add_shipping_information',{}, fb_eventid);
        {%- endif -%}
    }

    function callback_facebook_add_payment_information() {
        {%- if facebook -%}
            var fb_eventid = (new Date()).getTime() + '.' + Math.ceil(Math.random() * 10000000) + '.' + Math.ceil(Math.random() * 10000000);
            {%- for pixel in facebook -%}
            fbq('trackSingle', '{{ pixel.pixel_id }}', 'AddPaymentInfo',{}, {eventID: fb_eventid});
            {%- endfor -%}
            yfbservertag('AddPaymentInfo',{}, fb_eventid);
        {%- endif -%}
    }

    function callback_facebook_to_wishlist() {
        {% if facebook %}
        var fb_eventid = (new Date()).getTime() + '.' + Math.ceil(Math.random() * 10000000) + '.' + Math.ceil(Math.random() * 10000000);
        {% for pixel in facebook %}
        fbq('trackSingle', '{{ pixel.pixel_id }}', 'AddToWishlist', {}, { eventID: fb_eventid });
        {% endfor %}
        yfbservertag('AddToWishlist', {}, fb_eventid);
        {% endif %}
    }
  </script>

  <!-- End Facebook Pixel Code -->
{%- endif -%}